<template>
  <div class="app-container">
    <el-descriptions v-if="isNotNull(classScore)" style="width: 75%" labelClassName="descriptions-label-class"
                     :title="classScore.trainingClass.name" border size="mini" :column="4">
      <el-descriptions-item label="考试分值">{{classScore.firstExScore}}</el-descriptions-item>
      <el-descriptions-item label="评分表分值">{{classScore.firstTableScore}}</el-descriptions-item>
      <el-descriptions-item label="证书机构">{{isNotNull(classScore.firstCertOrganizationBean) ? classScore.firstCertOrganizationBean.name : ''}}</el-descriptions-item>
      <el-descriptions-item label="证书名称">{{isNotNull(classScore.firstCertTypeBean) ? classScore.firstCertTypeBean.name : ''}}</el-descriptions-item>
<!--      <el-descriptions-item label="复训考试分值">{{classScore.reExScore}}</el-descriptions-item>-->
<!--      <el-descriptions-item label="复训评分表分值">{{classScore.reTableScore}}</el-descriptions-item>-->
<!--      <el-descriptions-item label="复训证书机构">{{isNotNull(classScore.reCertOrganizationBean) ? classScore.reCertOrganizationBean.name : ''}}</el-descriptions-item>-->
<!--      <el-descriptions-item label="复训证书名称">{{isNotNull(classScore.reCertTypeBean) ? classScore.reCertTypeBean.name : ''}}</el-descriptions-item>-->
    </el-descriptions>
    <el-divider/>
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户名称" prop="userName">
        <el-input v-model="queryParams.userName" class="input-w-180" placeholder="请输入用户名称" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="用户姓名" prop="userName">
        <el-input v-model="queryParams.nickName" placeholder="请输入用户名称" clearable class="input-w-180" @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="上岗证" prop="postsNumber">
        <el-input v-model="queryParams.postsNumber" placeholder="请输入用户名称" clearable class="input-w-180" @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="手机号码" prop="phonenumber">
        <el-input v-model="queryParams.phonenumber" placeholder="请输入手机号码" clearable class="input-w-180" @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="合格状态">
        <!-- 合格 -->
        <el-select v-model="queryParams.params.qualified" placeholder="合格状态" clearable class="input-w-180">
          <el-option :key="1" label="合格" :value="1"/>
          <el-option :key="0" label="不合格" :value="0"/>
        </el-select>
        <!--        <el-tooltip content="是否合格" placement="top">-->
        <!--          <el-switch v-model="queryParams.params.qualified" @change="getList" :active-value="1" :inactive-value="0"/>-->
        <!--        </el-tooltip>-->
      </el-form-item>
      <el-form-item label="状态" prop="params.status">
        <el-select v-model="queryParams.params.status" placeholder="用户状态" clearable class="input-w-180">
          <el-option v-for="dict in dict.type.pv_study_record_status" :key="dict.value" :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form-item>
<!--      <el-form-item label="初复训" prop="params.initial">-->
<!--        <el-select v-model="queryParams.params.initial" placeholder="初复训" clearable class="input-w-180">-->
<!--          <el-option key="0" label="初训" value="0"/>-->
<!--          <el-option key="1" label="复训" value="1"/>-->
<!--        </el-select>-->
<!--      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button v-if="isFask" type="primary" plain icon="el-icon-magic-stick" size="mini" @click="handleCompleteCert">批量颁证</el-button>
        <el-button v-else type="danger" plain icon="el-icon-loading" size="mini" :disabled="false">任务正在处理</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-s-custom" size="mini" @click="openMoreStudent" v-hasPermi="['pv:training_class:add']">批量添加学员</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" icon="el-icon-download" @click="exportExcel" plain size="mini">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['pv:stu_record:remove']">删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange" :row-class-name="tableRowClassName" @sort-change="sortChange">
      <el-table-column type="selection" width="50" align="center"/>
      <el-table-column label="头像" align="center" width="50">
        <template slot-scope="scope">
          <viewer v-if="scope.row.student.avatar != undefined && scope.row.student.avatar != null && scope.row.student.avatar != ''">
            <el-avatar size="large" :src="scope.row.student.avatar"></el-avatar>
          </viewer>
          <el-avatar v-else size="large" src=""></el-avatar>
        </template>
      </el-table-column>
      <el-table-column label="姓名" align="center" prop="student.nickName" :show-overflow-tooltip="true" width="100"/>
      <el-table-column label="上岗证" align="center" prop="student.postsNumber" :show-overflow-tooltip="true" width="130"/>
      <el-table-column label="联系方式" align="center" prop="student.phonenumber" width="130"/>
<!--      <el-table-column label="初复训" align="center" width="100">-->
<!--        <template slot-scope="scope">-->
<!--          <el-tag v-if="scope.row.student?.userInfo?.reservedOne == '1'">复训</el-tag>-->
<!--          <el-tag v-else type="success">初训</el-tag>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="考试分数" prop="score" align="center" width="100" sortable></el-table-column>
<!--      <el-table-column label="总分" prop="puerperaTotalPoints" align="center" width="100"></el-table-column>-->
<!--      <el-table-column label="新生儿总分" prop="childrenTotalPoints" align="center" width="100"></el-table-column>-->
      <el-table-column label="评分表总分" prop="scoreTotal" align="center" width="120" sortable></el-table-column>
      <el-table-column label="备注" prop="puerperaComment" align="center"></el-table-column>
<!--      <el-table-column label="新生儿备注" prop="childrenComment" align="center"></el-table-column>-->
      <el-table-column label="状态" align="center" prop="status" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.pv_study_record_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="130" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-if="scope.row.status == '0'" size="mini" type="text" icon="el-icon-magic-stick" @click="completeCourse(scope.row.id)">结业</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
      <el-table-column type="expand" label="更多">
        <template slot-scope="scope">
          <el-descriptions :column="5" size="mini" border>
            <el-descriptions-item label="工作单位">{{scope.row.student.userInfo?.workUnit}}</el-descriptions-item>
            <el-descriptions-item label="社区"><el-tag size="mini" effect="plain" type="warning">{{scope.row.student.userInfo?.community}}</el-tag></el-descriptions-item>
            <el-descriptions-item label="执业范围">{{scope.row.student.userInfo?.practiceRange}}</el-descriptions-item>
            <el-descriptions-item label="执业类别">{{scope.row.student.userInfo?.practiceType}}</el-descriptions-item>
            <el-descriptions-item label="所在科室/岗位">{{scope.row.student.userInfo?.posts}}</el-descriptions-item>
          </el-descriptions>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList"/>

    <!-- 批量添加学员弹窗 -->
    <el-dialog title="批量添加学员" center :visible.sync="more_student.open" width="660px" append-to-body>
      <table>
        <tr>
          <td>
            <el-button class="fr mb10" type="primary" :disabled="isEmptyArr(more_student.insert_list)" @click="addMoreStudent" plain>添加</el-button>
          </td>
        </tr>
        <tr>
          <td>
            <el-transfer v-loading="loading" class="ml10 fr" filterable :filter-method="filterMethod" filter-placeholder="请输入学生姓名"
                         v-model="more_student.insert_list" :data="more_student.studentList"></el-transfer>
          </td>
        </tr>
      </table>
    </el-dialog>
  </div>
</template>

<script>
import {
  studentList,
  updateStu_record,
  complete_cert_ids,
  complete_cert_query,
  get_not_in_class_student_list, add_more_student, delStu_record
} from '@/api/pv/stu_record';
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

import {listCert_type} from "@/api/cert/cert_type";
import {listCert_organization} from "@/api/cert/cert_organization";
import {isEmptyArr} from '@/utils/zzDouUtils/arrayUtil'
import {isEmptyStr, isNull} from "@/utils/zzDouUtils/ObjUtil";

export default {
  name: "User",
  dicts: ['sys_user_sex' , 'pv_study_record_status'],
  data() {
    return {
      filterMethod(query, item){
        return item.label.indexOf(query) > -1;
      },
      more_student:{
        open: false,
        studentList:null,
        insert_list:[],
      },
      classId: null,
      // 颁证机构
      cert_organizationList: [],
      // 颁证类型
      cert_TypeList: [],
      cert:{
        classId: null,
        certOrganizationId: null,
        certTypeId: null,
      },
      title: null,
      open: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      deleteids:[],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: [],
      //培训班分值
      classScore:null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phonenumber: undefined,
        status: undefined,
        deptId: undefined,
        params:{},
      },
      // 表单校验
      rules: {
        certOrganizationId: [
          {required: true, message: "请选择颁证机构", trigger: "blur"}
        ],
        certTypeId: [
          {required: true, message: "请选择证书类型", trigger: "blur"}
        ],
      },
      //是否存在任务
      isFask:false,
    };
  },
  created() {
    this.classId = this.$route.params && this.$route.params.classId;
    this.getList();
    this.getOrganizationList();
    this.getCertTypeListList();
  },
  methods: {
    /** 批量添加学员 */
    addMoreStudent(){
      add_more_student(this.classId,this.more_student.insert_list).then(response=>{
        this.getList();
        this.more_student.studentList = [];
        this.more_student.insert_list = [];
        this.$notify.success('添加成功');
        this.more_student.open = false;
      })
    },
    /** 查询未报名的学员 */
    getNotInClassStudentList(){
      this.more_student.studentList = [];
      this.loading = true;
      get_not_in_class_student_list(this.classId).then(response=>{
        this.more_student.studentList = response.data;
        this.loading = false;
      })
    },
    /** 打开添加学员弹窗 */
    async openMoreStudent(){
      await this.getNotInClassStudentList();
      this.more_student.open = true;
    },
    /** 查询颁发类型列表 */
    getCertTypeListList() {
      listCert_type({pageSize: 1000, pageNum: 1}).then(response => {
        this.cert_TypeList = response.rows;
      });
    },
    /** 查询颁发机构列表 */
    getOrganizationList() {
      listCert_organization({pageSize: 1000, pageNum: 1}).then(response => {
        this.cert_organizationList = response.rows;
      });
    },
    /** 导出 */
    exportExcel(){
      this.download('/pv/stu_record/export/'+this.classId, {
        ...this.queryParams
      }, `${this.classScore.trainingClass.name}_${new Date().getTime()}.xlsx`)
    },
    /** 排序改变事件 */
    sortChange(column){
      if (column.prop == 'score'){
        this.queryParams.params.scoreOrder = isNull(column.order) ? null : (column.order == 'ascending') ? 'ASC' : 'DESC';
        this.queryParams.params.tableScoreOrder = null;
      }else if (column.prop == 'scoreTotal'){
        this.queryParams.params.tableScoreOrder = isNull(column.order) ? null : (column.order == 'ascending') ? 'ASC' : 'DESC';
        this.queryParams.params.scoreOrder = null;
      }
      this.getList()
    },
    /** 查询用户列表 */
    getList() {
      this.loading = true;
      studentList(this.classId,this.queryParams).then(response => {
          //排序
          if (response.rows.length > 0){
            this.userList = response.rows.map(o=>{
              if (isNull(o.exStudyReload)){
                o.score = 0;
              }else{
                o.score = (isNull(o.exStudyReload.score)) ? 0 : o.exStudyReload.score;
              }
              return o;
            })
          }else{
            this.userList = []
          }
          this.classScore = response.info;
          this.total = response.total;
          this.isFask = response.data;
          this.loading = false;
        }
      );
    },
    tableRowClassName({row, rowIndex}) {
      const userType = row.student.userInfo.reservedOne;
      const comparisonScore = userType == '0' ? this.classScore.firstExScore : this.classScore.reExScore;
      if (row.score < comparisonScore) {
        return 'warning-row';
      }
      return '';
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.student.userId);
      this.deleteids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    openCert(){
      this.open = true;
    },
    cancel(){
      this.open = false;
      this.reset();
    },
    reset(){
      this.form = {
        classId: this.classId,
        certOrganizationId: null,
        certTypeId: null,
      }
    },
    /** 批量颁证 */
    handleCompleteCert() {
      // this.$refs["cert"].validate(valid => {
      //   if (valid) {
      //     this.cert.classId = this.classId;
      //     this.cert.student = this.queryParams;
      //     this.$modal.confirm(isEmpty(this.ids) ? '是否按查询条件批量颁证':'是否将选中用户颁证').then(()=> {
      //       return flag ? complete_cert_query(this.cert,this.queryParams) : complete_cert_ids(this.cert,this.ids);
      //     }).then(() => {
      //       this.getList();
      //       this.cancel();
      //       this.reset();
      //       this.$modal.msgSuccess("任务正在后台执行中");
      //     }).catch(() => {});
      //   }
      // });
      this.cert.classId = this.classId;
      this.cert.student = this.queryParams;
      const flag = isEmptyArr(this.ids);
      this.$modal.confirm(flag ? '是否按查询条件批量颁证':'是否将选中用户颁证').then(()=> {
        return flag ? complete_cert_query(this.cert,this.queryParams) : complete_cert_ids(this.cert,this.ids);
      }).then(() => {
        this.getList();
        this.cancel();
        this.reset();
        this.$modal.msgSuccess("任务正在后台执行中");
      }).catch(() => {});
    },
    completeCourse(id){
      const recordForm = {id:id,status:'1'};
      updateStu_record(recordForm).then(response => {
        this.$modal.msgSuccess("结业成功");
        this.getList();
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.deleteids;
      this.$modal.confirm('是否确认删除学员报名记录编号为"' + ids + '"的数据项？').then(function () {
        return delStu_record(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
  }
};
</script>

<style>
.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.descriptions-label-class{
  width: 120px;
}
/* 穿梭框 */
.el-transfer-panel{
  width: 200px;
  height: 700px;
}
.el-transfer-panel__list.is-filterable{
  height: 700px;
}
</style>
